package com.qfedu.mtl.controller;

import com.alibaba.fastjson.JSON;
import com.qfedu.mtl.dto.LoginDto;
import com.qfedu.mtl.entity.Managers;
import com.qfedu.mtl.entity.Menus;
import com.qfedu.mtl.query.managerQuery;
import com.qfedu.mtl.service.ManagerService;
import com.qfedu.mtl.service.impl.ManagerServiceImpl;
import com.qfedu.mtl.util.CharacterUtil;
import com.qfedu.mtl.util.HttpUtil;
import com.qfedu.mtl.util.StrUtil;
import com.qfedu.mtl.util.page.Pager;
import com.qfedu.mtl.util.web.annotation.Controller;
import com.qfedu.mtl.util.web.annotation.RequestMapping;
import com.qfedu.mtl.vo.TableVO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Controller
@RequestMapping("/manager")
public class ManagerController {
    //声明业务对象
    private ManagerService managerService= new ManagerServiceImpl();

    //处理登录请求的接口
    @RequestMapping("/login.do")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {


        CharacterUtil.setContentWithJson(request, response);
        LoginDto loginDto = HttpUtil.request2Bean(request, LoginDto.class);
        Managers manager = managerService.login(loginDto);
        Map<String,Object> vo = new HashMap<>();
        //比较验证码
        String realCode = request.getSession().getAttribute("captcha_login").toString();
        String userCode = loginDto.getCode();
        if(!realCode.equalsIgnoreCase(userCode)){
            //验证码
            vo.put("errorCode",-2);
            vo.put("msg","验证码错误");
            vo.put("data",null);

        }else

        if (manager!=null){
            //成功
            vo.put("errorCode",0);
            vo.put("msg","登录成功");
            vo.put("data",manager);
            request.getSession().setAttribute("current",manager);
        }else{
            //失败
            vo.put("errorCode",-1);
            vo.put("msg","账号或密码错误");
            vo.put("data",null);
        }
        String json = JSON.toJSONString(vo);

        response.getWriter().print(json);
    }

    //处理安全退出的请求接口
    @RequestMapping("/logout.do")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CharacterUtil.setContentWithJson(request, response);
        //删除保存的用户session
        request.getSession().removeAttribute("current");
        response.sendRedirect("/dist/views/user/login.html");
    }

    //处理列表的请求接口
    @RequestMapping("/list.do")
    public void list(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CharacterUtil.setContentWithJson(request, response);
        String page = request.getParameter("page");
        page = StrUtil.ifNull(page,"1");
        String size = StrUtil.ifNull(request.getParameter("size"), "5");
        managerQuery userQuery = HttpUtil.request2Bean(request, managerQuery.class);
        ManagerService userService = new ManagerServiceImpl();
        Pager<Managers> pageQuery = userService.findPageQuery(Integer.valueOf(page), Integer.valueOf(size), userQuery);
        //使用专门的vo进行响应
        TableVO vo = TableVO.from(pageQuery);
        //响应
        String json = JSON.toJSONString(vo);
        response.getWriter().print(json);

    }

    //处理渲染菜单的请求接口
    @RequestMapping("/menus.do")
    public void menus(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CharacterUtil.setContentWithJson(request, response);
        Managers manager = (Managers) request.getSession().getAttribute("current");
        Integer mgrId = manager.getMgrId();
        //业务层返回查询到的菜单
        List<Menus> treeList = managerService.findSelfMenus(mgrId);
        //返回给前端
        HttpUtil.responseSuccess(treeList,response);

    }

    //处理添加的请求接口
    @RequestMapping("/add.do")
    public void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String,Object> vo = new HashMap<>();
        CharacterUtil.setContentWithJson(request, response);
        Managers dto = HttpUtil.request2Bean(request, Managers.class);
        int row = managerService.sava(dto);
        if (row>0){
            //成功
            vo.put("errorCode",0);
            vo.put("msg","添加成功");
            vo.put("data",dto);
        }else{
            vo.put("errorCode",-1);
            vo.put("msg","添加失败，信息已存在");
            vo.put("data",null);
        }
        //输出
        response.getWriter().println(JSON.toJSONString(vo));

    }

    //处理修改编辑的请求接口
    @RequestMapping("/update.do")
    public void editById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CharacterUtil.setContentWithJson(request, response);
        ///前端数据不能有下划线，有下划线需要下划线转驼峰
        Managers manager = HttpUtil.request2Bean(request, Managers.class);
        int row = managerService.editById(manager);
        if (row>0){
            HttpUtil.responseSuccess(null,response);
        }else{
            HttpUtil.response(null,-1,"操作失败，信息已存在",response);
        }
    }

    //处理删除的请求接口
    @RequestMapping("/del.do")
    public void delById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CharacterUtil.setContentWithJson(request, response);
        String id = request.getParameter("id");
        if (StrUtil.isNullOrEmpty(id)){
            HttpUtil.response(null,-1,"请选择删除的id",response);
            return;
        }
        try{
            managerService.delById(Integer.valueOf(id));
            HttpUtil.responseSuccess(null,response);
        }catch (Exception e){
            HttpUtil.response(null,-1,e.getMessage(),response);
        }

    }

    //处理批量删除的请求接口
    @RequestMapping("/delBatch.do")
    public void delByIdBatch(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CharacterUtil.setContentWithJson(request, response);
        String id = request.getParameter("id");  //  id  =》1,2,3
        //卫语句,防止前端传入空的id
        if (StrUtil.isNullOrEmpty(id)){
            HttpUtil.response(null,-1,"请选择要删除的id",response);
            return;
        }
        //分割
        String[] idss = id.split(",");
        //转为整型集合
        List<Integer> ids = Stream.of(idss).map(e -> Integer.valueOf(e)).collect(Collectors.toList());
        //尝试批量删除
        try {
            managerService.delByIdBatch(ids);
            HttpUtil.responseSuccess(null,response);
        }catch (Exception e){
            HttpUtil.response(null,-1,e.getMessage(),response);
        }
    }

}
